﻿' ----------------------------------------------------------------------------------
' Microsoft Developer & Platform Evangelism
' 
' Copyright (c) Microsoft Corporation. All rights reserved.
' 
' THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
' EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES 
' OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
' ----------------------------------------------------------------------------------
' The example companies, organizations, products, domain names,
' e-mail addresses, logos, people, places, and events depicted
' herein are fictitious.  No association with any real company,
' organization, product, domain name, email address, logo, person,
' places, or events is intended or should be inferred.
' ----------------------------------------------------------------------------------

Imports System.Security.Cryptography.X509Certificates
Imports System.Globalization

Namespace Infrastructure

    Public NotInheritable Class CertificateUtil
        Private Sub New()
        End Sub

        Public Shared Function GetCertificate(ByVal name As StoreName, ByVal location As StoreLocation, ByVal thumbprint As String) As X509Certificate2
            Dim store = New X509Store(name, location)
            Dim certificates As X509Certificate2Collection = Nothing
            store.Open(OpenFlags.ReadOnly)

            Try
                Dim result As X509Certificate2 = Nothing

                ' Every time we call store.Certificates property, a new collection will be returned.
                certificates = store.Certificates

                For i As Integer = 0 To certificates.Count - 1
                    Dim cert As X509Certificate2 = certificates(i)

                    If cert.Thumbprint.Equals(thumbprint, StringComparison.OrdinalIgnoreCase) Then
                        result = New X509Certificate2(cert)
                        Exit For
                    End If
                Next i

                If result Is Nothing Then
                    Throw New ApplicationException(String.Format(CultureInfo.InvariantCulture, "No certificate was found for thumbprint {0}", thumbprint))
                End If

                Return result
            Finally
                If certificates IsNot Nothing Then
                    For i As Integer = 0 To certificates.Count - 1
                        Dim cert As X509Certificate2 = certificates(i)
                        cert.Reset()
                    Next i
                End If

                store.Close()
            End Try
        End Function
    End Class
End Namespace